//
//  LuckyScreenWnd.m
//  SMTools
//
//  Created by fengsh on 2018/12/29.
//  Copyright © 2018年 fengsh. All rights reserved.
//

#import "LuckyScreenWnd.h"
#import "LuckyApi.h"
#import <Masonry/Masonry.h>
#import "LuckyRandomView.h"
#import <SDWebImage/SDWebImageManager.h>
#import "LuckyUtils.h"
#import "LuckyEmployees.h"
#import <MagicalRecord/MagicalRecord.h>
#import <QuartzCore/QuartzCore.h>

@interface LuckyScreenWnd ()<NSWindowDelegate>
@property (weak) IBOutlet NSButton *btn_start;
@property (weak) IBOutlet NSImageView *img_bg;
///随机显示view
@property (nonatomic, strong) LuckyRandomView                   *rv;
@property (weak) IBOutlet   NSView                              *contentview;
///效果使用的数据，非真实抽奖数据源
@property (nonatomic, strong) NSMutableArray                    *randomDataset;
@property (nonatomic, strong) dispatch_queue_t                  queue;
@property (nonatomic, strong) NSTimer                           *timer;
@property (nonatomic, assign) NSInteger                         randomcount;

@end

@implementation LuckyScreenWnd

- (void)windowDidLoad
{
    [super windowDidLoad];
    
    self.queue = dispatch_queue_create("com.fsh.random", 0);
    self.btn_start.allowsMixedState = NO;
    [self.btn_start setButtonType:NSButtonTypeOnOff];
    self.btn_start.state = NSOffState;
    self.window.delegate = self;
    
    CGFloat w = CGRectGetWidth([NSScreen mainScreen].frame);
    CGFloat h = CGRectGetHeight([NSScreen mainScreen].frame);

    //背景图
    self.img_bg.image = [NSImage imageNamed:@"bg"];
    [self.img_bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(@(0));
        make.width.equalTo(@(w));
        make.height.equalTo(@(h));
    }];
    
    self.rv = [[LuckyRandomView alloc]init];
    [self.rv.lb_random_phone setStringValue:@"13869990034"];
    [self.rv.lb_random_name setStringValue:@"爱新觉罗"];
    [self.contentview addSubview:self.rv];
    
    [self.rv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(w*0.2));
        make.height.equalTo(@(h*0.4));
        make.centerX.equalTo(@(0));
        make.centerY.equalTo(@(0)).offset(-200);
    }];
    
    [self loadLocalDatas];
    /*
    NSString *st = @"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKAD8u1YHTEAUcMB9cWYm3F2aqvgyCND5ibmibOXFp6z3RiawKFkkmiaHk7VlskJlTjLm2FjayYlVKUhw/132";
    NSURL *av = [NSURL URLWithString:st];
    [[SDWebImageManager sharedManager]loadImageWithURL:av options:SDWebImageRetryFailed progress:nil completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        
        
        
        self.rv.img_rand.image = [LuckyUtils resizeImage:image size:self.rv.img_rand.frame.size];
    }];
     */
    
    //隐藏菜单
    [NSMenu setMenuBarVisible:NO];
    if (@available(macOS 10.10, *)) {
        self.window.titleVisibility = NSWindowTitleHidden;
        self.window.titlebarAppearsTransparent = YES;
    } else {
        // Fallback on earlier versions
    }
    
//    self.window.styleMask = NSTitledWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask | NSClosableWindowMask | NSTexturedBackgroundWindowMask;
    
    ///使用这个mask不可以拖动，当多屏显示的情况下，主程序在那个屏，就在那个屏上全屏。
    self.window.styleMask = NSResizableWindowMask | NSClosableWindowMask | NSTexturedBackgroundWindowMask;
    self.window.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary | NSWindowCollectionBehaviorFullScreenAuxiliary;

    ///成为全屏
    [self.window toggleFullScreen:nil];
}

- (void)dealloc
{
    NSLog(@"全屏Free.");
}

- (void)loadLocalDatas
{
    NSArray *arr = [LuckyEmployees MR_findAll];
    if (arr) {
        self.randomDataset = [NSMutableArray arrayWithArray:arr];
    }
    
    self.randomcount = arr.count;
}


- (void)windowWillEnterFullScreen:(NSNotification *)notification
{
    NSLog(@"windowWillEnterFullScreen %@",NSStringFromRect(self.window.frame));
    
}


- (NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOption
{
    return NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideToolbar | NSApplicationPresentationAutoHideMenuBar |NSApplicationPresentationAutoHideDock ;
}


- (BOOL)inFullScreenMode {
    NSApplicationPresentationOptions opts = [NSApp presentationOptions];
    if ( opts & NSApplicationPresentationFullScreen) {
        return YES;
    }
    return NO;
}

- (IBAction)onCloseClicked:(id)sender
{
    [NSMenu setMenuBarVisible:YES];
    [self.timer invalidate];
    self.timer = nil;
    [self.window close];
}

- (IBAction)onStartClicked:(NSButton *)sender
{
    [self makeFireworksDisplay];
    return;
    
    BOOL isOn = sender.state;
    [sender setTitle:isOn?@"停止":@"开始"];
    if (isOn) {
        NSLog(@"执行");
        [self startRandomAnimate];
    } else {
        NSLog(@"停止");
        [self stop];
    }

    return;
    NSInteger total = self.currentProject.count;
    NSInteger remaincount = self.currentProject.remain_count;
    NSInteger current = (total - remaincount) + 1;
    if (current > total) { //不能操了
        return;
    }
    NSDictionary *p = @{@"prizeLevelId":@(self.currentProject.id),@"count":@(current)};
    [[LuckyApi api]lucky_api_post_queryLucyResult:p comletion:^(id respobj, NSError *error) {
        if (!error) {
            NSLog(@"%@",respobj);
        }
    }];
}

- (void)startRandomAnimate
{
    if (!self.timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.050 target:self selector:@selector(onRandom:) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

- (void)stop
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)onRandom:(NSTimer*)tm
{
    //0~self.randomcount-1
    NSInteger r = arc4random_uniform((int32_t)self.randomcount);
    
    LuckyEmployees *emp = self.randomDataset[r];
    NSString *st = emp.photo;
    NSURL *av = [NSURL URLWithString:st];
    [[SDWebImageManager sharedManager]loadImageWithURL:av options:SDWebImageRetryFailed progress:nil completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        self.rv.img_rand.image = [LuckyUtils resizeImage:image size:self.rv.img_rand.frame.size];
    }];
    
    [self.rv.lb_random_name setStringValue:emp.name?:@""];
    [self.rv.lb_random_phone setStringValue:emp.phone?:@""];
}

/*
 CAEmitterLayer 可能用到是属性
 * birthRate:粒子产生系数，默认1.0；
 * emitterCells: 装着CAEmitterCell对象的数组，被用于把粒子投放到layer上；
 * emitterDepth:决定粒子形状的深度联系：emittershape
 * emitterMode:发射模式
 * emitterPosition:发射位置
 * emitterShape:发射源的形状;
 * emitterSize:发射源的尺寸大；
 * emitterZposition:发射源的z坐标位置；
 * lifetime:粒子生命周期
 * preservesDepth:不是多很清楚（粒子是平展在层上）
 * renderMode:渲染模式：
 * scale:粒子的缩放比例：
 * seed：用于初始化随机数产生的种子
 * spin:自旋转速度
 * velocity：粒子速度
 
 
 //CAEmitterCell 可能用到的属性
 * birthRate 这个必须要设置，具体含义是每秒某个点产生的effectCell数量
 * alphaRange:  一个粒子的颜色alpha能改变的范围；
 * alphaSpeed:粒子透明度在生命周期内的改变速度；
 * blueRange：一个粒子的颜色blue 能改变的范围；
 * blueSpeed: 粒子blue在生命周期内的改变速度；
 * color:粒子的颜色
 * contents：是个CGImageRef的对象,既粒子要展现的图片；
 * contentsRect：应该画在contents里的子rectangle：
 * emissionLatitude：发射的z轴方向的角度
 * emissionLongitude:x-y平面的发射方向
 * emissionRange；周围发射角度
 * emitterCells：粒子发射的粒子
 * enabled：粒子是否被渲染
 * greenrange: 一个粒子的颜色green 能改变的范围；
 * greenSpeed: 粒子green在生命周期内的改变速度；
 * lifetime：生命周期
 * lifetimeRange：生命周期范围
 * magnificationFilter：不是很清楚好像增加自己的大小
 * minificatonFilter：减小自己的大小
 * minificationFilterBias：减小大小的因子
 * name：粒子的名字
 * redRange：一个粒子的颜色red 能改变的范围；
 * redSpeed; 粒子red在生命周期内的改变速度；
 * scale：缩放比例：
 * scaleRange：缩放比例范围；
 * scaleSpeed：缩放比例速度：
 * spin：子旋转角度
 * spinrange：子旋转角度范围
 * style：不是很清楚：
 * velocity：速度
 * velocityRange：速度范围
 * xAcceleration:粒子x方向的加速度分量
 * yAcceleration:粒子y方向的加速度分量
 * zAcceleration:粒子z方向的加速度分量
 
*/

- (void)makeFireworksDisplay {
    // 粒子发射系统 的初始化
    CAEmitterLayer *fireworksEmitter = [CAEmitterLayer layer];
    CGRect viewBounds = self.window.contentView.bounds;//self.view.layer.bounds;
    // 发射源的位置
    fireworksEmitter.emitterPosition = CGPointMake(viewBounds.size.width/2.0, viewBounds.size.height);
    // 发射源尺寸大小
    fireworksEmitter.emitterSize = CGSizeMake(viewBounds.size.width/2.0, 0.0);
    // 发射模式
    fireworksEmitter.emitterMode = kCAEmitterLayerOutline;
    // 发射源的形状
    fireworksEmitter.emitterShape = kCAEmitterLayerLine;
    // 发射源的渲染模式
    fireworksEmitter.renderMode = kCAEmitterLayerAdditive;
    // 发射源初始化随机数产生的种子
    fireworksEmitter.seed = (arc4random()%100)+1;
    
    /**
     *  添加发射点
     一个圆（发射点）从底下发射到上面的一个过程
     */
    CAEmitterCell* rocket  = [CAEmitterCell emitterCell];
    rocket.birthRate = 1.0; //是每秒某个点产生的effectCell数量
    rocket.emissionRange = 0.25 * M_PI; // 周围发射角度
    rocket.velocity = 400; // 速度
    rocket.velocityRange = 100; // 速度范围
    rocket.yAcceleration = 75; // 粒子y方向的加速度分量
    rocket.lifetime = 1.02; // effectCell的生命周期，既在屏幕上的显示时间要多长。
    
    // 下面是对 rocket 中的内容，颜色，大小的设置
    NSImage *sourc = [NSImage imageNamed:@"FFRing"];
    rocket.contents = (id) [self NSImageToCGImageRef:sourc];
    rocket.scale = 0.2;
    rocket.color = [NSColor redColor].CGColor;//[[UIColor redColor] CGColor];
    rocket.greenRange = 1.0;
    rocket.redRange = 1.0;
    rocket.blueRange = 1.0;
    rocket.spinRange = M_PI; // 子旋转角度范围
    
    /**
     * 添加爆炸的效果，突然之间变大一下的感觉
     */
    CAEmitterCell* burst = [CAEmitterCell emitterCell];
    burst.birthRate = 1.0;
    burst.velocity = 0;
    burst.scale = 2.5;
    burst.redSpeed =-1.5;
    burst.blueSpeed =+1.5;
    burst.greenSpeed =+1.0;
    burst.lifetime = 0.35;
    
    /**
     *  添加星星扩散的粒子
     */
    CAEmitterCell* spark = [CAEmitterCell emitterCell];
    spark.birthRate = 400;
    spark.velocity = 125;
    spark.emissionRange = 2* M_PI;
    spark.yAcceleration = 75; //粒子y方向的加速度分量
    spark.lifetime = 3;
    
    NSImage *star = [NSImage imageNamed:@"FFTspark"];
    spark.contents = (id) [self NSImageToCGImageRef:star];
    spark.scaleSpeed =-0.2;
    spark.greenSpeed =-0.1;
    spark.redSpeed = 0.4;
    spark.blueSpeed =-0.1;
    spark.alphaSpeed =-0.25; // 例子透明度的改变速度
    spark.spin = 2* M_PI; // 子旋转角度
    spark.spinRange = 2* M_PI;
    
    // 将 CAEmitterLayer 和 CAEmitterCell 结合起来
    fireworksEmitter.emitterCells = [NSArray arrayWithObject:rocket];
    //在圈圈粒子的基础上添加爆炸粒子
    rocket.emitterCells = [NSArray arrayWithObject:burst];
    //在爆炸粒子的基础上添加星星粒子
    burst.emitterCells = [NSArray arrayWithObject:spark];
    // 添加到图层上
    [self.window.contentView.layer addSublayer:fireworksEmitter];
}


- (CGImageRef)NSImageToCGImageRef:(NSImage*)image{
    
    NSData * imageData = [image TIFFRepresentation];
    
    CGImageRef imageRef;
    
    if(imageData){
        
        CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
        
        imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
        
    }
    
    return imageRef;
    
}

@end
